package com.sen.gulimall.ware.config;

import com.sen.common.constant.WareConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Kisen
 * @email lqs0911@qq.com
 * @date 2022/11/18 11:38
 * @detail
 */
@Configuration
public class RabbitMQConfig {

    /**
     * 使用JSON序列化机制，进行消息转换
     *
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }


    /**
     * 解锁库存交换机
     *
     * @return
     */
    @Bean
    public TopicExchange stockEventExchange() {
        return ExchangeBuilder.topicExchange(WareConstant.STOCK_EVENT_EXCHANGE)
                .durable(true)
                .build();
    }

    /**
     * 解锁库存延时队列
     *
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> arguments = new HashMap<>(3);
        // 声明当前队列绑定的死信交换机
        arguments.put("x-dead-letter-exchange", WareConstant.STOCK_EVENT_EXCHANGE);
        // 声明当前队列的死信路由 key
        arguments.put("x-dead-letter-routing-key", "stock.release");
        // 声明队列的TTL
        arguments.put("x-message-ttl", 2 * 60 * 1000);
        return QueueBuilder.durable(WareConstant.STOCK_DELAY_QUEUE)
                .withArguments(arguments)
                .build();
    }

    /**
     * 解锁库存队列
     *
     * @return
     */
    @Bean
    public Queue stockReleaseStockQueue() {
        return QueueBuilder.durable(WareConstant.STOCK_RELEASE_STOCK_QUEUE).build();
    }

    /**
     * 锁定库存绑定路由
     *
     * @param stockDelayQueue
     * @param stockEventExchange
     * @return
     */
    @Bean
    public Binding stockLockedBinding(@Qualifier("stockDelayQueue") Queue stockDelayQueue,
                                      @Qualifier("stockEventExchange") TopicExchange stockEventExchange) {
        return BindingBuilder.bind(stockDelayQueue).to(stockEventExchange).with(WareConstant.STOCK_LOCKED_ROUTING_KEY);
    }

    /**
     * 解锁库存绑定路由
     *
     * @param stockReleaseStockQueue
     * @param stockEventExchange
     * @return
     */
    @Bean
    public Binding stockReleaseBinding(@Qualifier("stockReleaseStockQueue") Queue stockReleaseStockQueue,
                                       @Qualifier("stockEventExchange") TopicExchange stockEventExchange) {
        return BindingBuilder.bind(stockReleaseStockQueue).to(stockEventExchange).with(WareConstant.STOCK_RELEASE_ROUTING_KEY);
    }

}
